$(function() {
    // 初始化操作事件
    initOperateEvents();

    // 初始化表格
    initTable();

    // 初始化表单验证
    initFormValidation();

    // 提交表单事件处理
    initFormSubmitHandler();
});

// 初始化操作事件
function initOperateEvents() {
    window.operateEvents = {
        'click .edit': function (e, value, row, index) {
            showEditModal(row);
        },
        'click .remove': function (e, value, row, index) {
            deleteStudent(row.id);
        }
    };
}

// 初始化表格
function initTable() {
    $("#students").bootstrapTable({
        method: "get",
        url: '/api/student/list3',
        cache: false,
        striped: true,
        pagination: true,
        sortable: false,
        sidePagination: "server",
        pageNumber: 1,
        pageSize: 3,
        pageList: [3, 5, 25],
        strictSearch: false,
        minimumCountColumns: 2,
        clickToSelect: true,
        uniqueId: "id",
        cardView: false,
        detailView: false,
        showFullscreen: true,
        showRefresh: true,
        showColumns: true,
        showColumnsToggleAll: true,
        queryParams: function(params) {
            return {
                pageSize: params.limit,
                pageNum: Math.floor(params.offset / params.limit) + 1
            };
        },
        columns: [{
            checkbox: true
        }, {
            field: 'id',
            title: '学生id'
        }, {
            field: 'no',
            title: '学号'
        }, {
            field: 'name',
            title: '姓名'
        }, {
            field: 'sex',
            title: '性别'
        }, {
            field: 'age',
            title: '年龄'
        }, {
            field: 'score',
            title: '分数'
        }, {
            field: 'operate',
            title: '操作',
            align: 'center',
            formatter: operateFormatter,
            events: operateEvents
        }]
    });
}

// 操作列的格式化函数
function operateFormatter(value, row, index) {
    return [
        '<a class="edit" style="margin-right: 15px;"  href="javascript:void(0)" title="编辑">',
        '<i class="fas fa-pencil-alt"></i>',
        '</a>  ',
        '<a class="remove " href="javascript:void(0)" title="删除">',
        '<i class="fas fa-times"></i>',
        '</a>'
    ].join('');
}

// 初始化表单验证
function initFormValidation() {
    $("#formStudent").validate({
        rules: {
            password: {
                required: false,
                minlength: 6
            }
        },
        messages: {
            password: {
                minlength: "密码必须是6位"
            }
        },
        submitHandler: function(form) {
            submitStudentForm();
        }
    });
}

// 提交表单事件处理
function initFormSubmitHandler() {
    $('#formStudent').off('submit').on('submit', function(e) {
        e.preventDefault();
        if ($(this).valid()) {
            // 使用submitHandler函数进行表单提交，避免递归调用
            $(this).validate().settings.submitHandler(this);
        }
    });
}

// 显示编辑模态框
function showEditModal(row) {
    $('#id').val(row.id);
    $('#no').val(row.no);
    $('#name').val(row.name);
    $('#password').val(''); // 设置为空，用户可以选择是否输入新密码
    $('#sex').val(row.sex);
    $('#age').val(row.age);
    $('#score').val(row.score);
    $('#myModal').modal('show');
}

// 删除学生信息
function deleteStudent(id) {
    if (confirm('确定删除该学生信息吗？')) {
        $.ajax({
            url: '/api/student/deletebyid/' + id,
            type: 'DELETE',
            success: function(result) {
                console.log('删除成功: ', result);
                $('#students').bootstrapTable('refresh');
            },
            error: function(xhr, status, error) {
                console.error('删除失败: ', status, error);
            }
        });
    }
}

// 提交学生表单
function submitStudentForm() {
    var id = $('#id').val();
    var formData = {
        id: id,
        no: $("#no").val(),
        name: $("#name").val(),
        password: $("#password").val(),
        sex: $("#sex").val(),
        age: $("#age").val(),
        score: $("#score").val()
    };
    // 如果密码为空，移除密码字段
    if (!formData.password) {
        delete formData.password;
    }
    var url, type;
    if (id == "0" || id == "") {
        url = "/api/student/insert";
        type = "POST";
    } else {
        url = "/api/student/update";
        type = "PUT";
    }
    $.ajax({
        url: url,
        type: type,
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(result) {
            console.log("操作成功: ", result);
            $('#myModal').modal('hide');
            $('#students').bootstrapTable('refresh');
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error("操作失败: ", textStatus, errorThrown);
        }
    });
}

// 提示新增学生
function preAdd() {
    $('#id').val("0"); //提示新增
    $('#formStudent').trigger('reset'); //重置表单
    $('#myModal').modal('show'); // 显示模态框
}

// 查询学生
function searchStudents() {
    var queryNo = $("#queryNo").val();
    var queryName = $("#queryName").val();
    var querySex = $("#querySex").val();
    var queryAgeRange = $("#queryAgeRange").val();
    var queryScoreRange = $("#queryScoreRange").val();

    var queryParams = {};
    if (queryNo !== "") queryParams.no = queryNo;
    if (queryName !== "") queryParams.name = queryName;
    if (querySex !== "") queryParams.sex = querySex;
    if (queryAgeRange !== "") queryParams.ageRange = queryAgeRange;
    if (queryScoreRange !== "") queryParams.scoreRange = queryScoreRange;

    $.ajax({
        url: "/api/student/search",
        type: "GET",
        data: queryParams,
        success: function(data) {
            console.log("查询成功: ", data);
            $('#students').bootstrapTable('load', data); // 使用新的数据更新表格
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error("查询失败: ", textStatus, errorThrown);
        }
    });
}
